<template>
  <div class="container">
    <h1>TODOLIST</h1>
    <div class="new">
      <input v-model.trim="content" type="text" @keyup.enter="add" />
      <button @click="add">新建</button>
    </div>
    <div class="todo-item" v-for="item in todoList" :key="item.id">
      <p v-show="!item.editState">{{ item.content }}</p>
      <input v-show="item.editState" type="text" v-model="item.content" />
      <button v-show="!item.editState" @click="edit(item.id)">修改</button>
      <button v-show="item.editState" @click="save(item.id)">保存</button>
      <button @click="del(item.id)">删除</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      content: "",
      todoList: [
        {
          id: 1,
          content: "吃饭",
          done: false,
          editState: false,
        },
        {
          id: 2,
          content: "睡觉",
          done: true,
          editState: false,
        },
      ],
    };
  },
  methods: {
    add() {
      if (this.content === "") {
        return alert("请输入任务名称");
      }
      const len = this.todoList.length;
      const id = len > 0 ? this.todoList[len - 1].id + 1 : 1;
      const todo = {
        id,
        content: this.content,
        editState: false,
      };
      this.todoList.push(todo);
      this.content = "";
    },
    del(id) {
      const index = this.todoList.findIndex((item) => item.id === id);
      this.todoList.splice(index, 1);
    },
    edit(id) {
      const index = this.todoList.findIndex((item) => item.id === id);
      this.todoList[index].editState = true;
    },
    save(id) {
      const index = this.todoList.findIndex((item) => item.id === id);
      this.todoList[index].editState = false;
    },
  },
};
</script>

<style>
.container {
  width: 80%;
  margin: auto;
}
.new,
.todo-item {
  border: 1px solid #eee;
  margin: 10px 0;
  padding: 10px;
}
</style>